package com.banmao.util;

import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.Callable;
import java.util.function.Predicate;

@Slf4j
public class RetryUtil<T> {

    public static <T> T retry(RetryProperty<T> retryProperty) throws Exception {
        // 测试重试框架
        RetryConfig config = RetryConfig.custom()
                .maxAttempts(retryProperty.getMaxAttempts())
                .waitDuration(retryProperty.getWaitDuration())
                .retryOnException(retryProperty.getRetryOnException())
                .build();

        Retry myRetry = Retry.of("myRetry", config);

        T res = myRetry.executeCallable(retryProperty.getCallable());
        return res;
    }

    @Data
    @Builder
    public static class RetryProperty<T> {

        private int maxAttempts;

        private Duration waitDuration;

        private Callable<T> callable;

        private Predicate<Throwable> retryOnException;

    }

}
